#! /usr/bin/env tclsh

# ----------------------------------------------------------------------------
# 
# Upgrade chia on a bunch of machines on the network.
#
# yqm_leaf@163.com
# 
# 05/06/21
#
# ----------------------------------------------------------------------------

package require Expect

#exp_internal 1

source [file join [file dirname [info script]] "lib.tcl"]

if {$argc != 1} {
    puts stderr "Usage: $argv0 \[upgrade_machines.txt]"
    exit 255
}

set machines [lindex $argv 0]

if {![file readable $machines]} {
    puts stderr "File: $machines unreadable"
    exit -1
}

set fd [open $machines "r"]
set file_data [read $fd]
close $fd
set data [split $file_data "\n"]
set _prompt "(.*)\[#>$] "

foreach line $data {
    # skip comment & empty lines.
    if {[regexp {^\s*#} $line] || [regexp {^\s*$} $line]} {
        continue
    }
    # Trim spaces.
    set line [string trim $line]
    #172.16.216.139 chia/chia /home/chia-blockchain/chia-blockchain
    if {[regexp {([\d\.]+)\s+([\w\/\.]+)\s+([\w\/\-]+)$} $line - \
        ip user_pass venv_dir]} {
        if {![valid_ipv4 $ip]} {
                puts stderr "Not a valid IP address: <$ip>"
                continue
        }
        if {![regexp {^(.*?)/(.*?)$} $user_pass - user pass]} {
            puts stderr "Not a valid user/password: $user_pass"
            continue
        }
        set spawn_id [login $ip $user $pass 120]
        send "\r"
        expect -re "$_prompt" {
            send "cd $venv_dir\r"
        }
        set timeout 300
        expect -re "$_prompt" {
            send "git pull\r"
        } timeout {
            puts stderr "Timeout"
            exit -1
        }
        expect -re "$_prompt" {
            send "bash install.sh\r"
        } timeout {
            puts stderr "Timeout"
        }
        expect -re "$_prompt" {
            send "exit\r"
        }
    } else {
        puts stderr "Not a valid line: $line"
        continue
    }
}
